import React, { useState, useEffect, useImperativeHandle } from 'react';
import { Row, Col, Button } from 'antd';
import { randomKey } from '../../../../utils/utils';
import { STRATEGY_MODE } from '../../../../utils/constant';
import RuleItem from './ruleItem';
import OtherBtn from './otherBtn';
/**
 * @component Rules 规则配置组件
 * @prop {Array} value 组件值
 *
 * @prop {Boolean} isShowRules 是否展示具体的配置项 , 默认false
 * @prop {Function} onChange 改变值之后的回调
 * @prop {Object} variable 可被用于选择的变量对象
 * @prop {Boolean} disabled 是否只读,默认false
 */

export default function Rules(props) {
  const [rules, setRules] = useState(props.value || []);

  useImperativeHandle(props.createRef, () => ({
    // 暴露方法给父组件,收集值，验证应该放到这里，后面再做
    getValue: () => {
      return rules;
    },
  }));
  useEffect(() => {
    console.log(props.value);
    if (props.value && props.value.length > 0) {
      setRules(initData(props.value));
    } else {
      addRule();
    }
  }, [props.value]);

  function initData(data) {
    const newData = data.map((item) => {
      item.id = item.id ? item.id : randomKey();
      return item;
    });
    return newData;
  }

  //添加规则
  function addRule() {
    const rule = {
      name: '',
      condition: {},
      enabled: true,
      id: randomKey(),
    };
    rules.push(rule);
    setRules(Object.assign([], rules));
    // props.onChange && props.onChange(rules);
  }

  // 修改item的value回调
  function handleChange(id, value) {
    for (let i = 0; i < rules.length; i++) {
      if (rules[i].id === id) {
        rules[i] = value;
      }
    }
    // console.log(rules)
    setRules(Object.assign([], rules));
    // props.onChange && props.onChange(rules);
  }

  // 删除
  function del(index) {
    rules.splice(index, 1);
    setRules(Object.assign([], rules));
    // props.onChange && props.onChange(rules);
  }

  // 移动
  function move(item, index, step) {
    // 下移
    if (step === 'down') {
      rules.splice(index, 1); //移除当前项
      rules.splice(index + 1, 0, item); // 在index+1处插入当前item
      // 上移
    } else if (step === 'up') {
      rules.splice(index, 1); //移除当前项
      rules.splice(index - 1, 0, item); // 在index-1处插入当前item
    }
    setRules(Object.assign([], rules));
    // props.onChange && props.onChange(rules);
  }
  // console.log(rules);
  return (
    <>
      {!props.hidden && (
        <div style={{ marginTop: '20px' }} className='rule-wp'>
          {!props.disabled && (
            <Row type='flex' justify='start' gutter={10} style={{ marginBottom: '10px' }}>
              <Col>
                <Button
                  type='primary'
                  onClick={() => {
                    addRule();
                  }}
                  disabled={!props.isShowRules}
                >
                  添加规则
                </Button>
              </Col>
              {props.mode === STRATEGY_MODE._WEIGHT && <OtherBtn {...props} onComplete={props.reloadVariable} />}
            </Row>
          )}
          <Row type='flex' justify='space-between' align='middle' gutter={10} className='rule-hd'>
            <Col span={1}>序号</Col>
            <Col span={3}>规则名称</Col>
            <Col span={3}>左变量</Col>
            <Col span={3}>操作符</Col>
            <Col span={3}>右变量</Col>
            <Col span={2}>启用</Col>
            {props.mode === STRATEGY_MODE._WEIGHT && <Col span={6}>权重计算</Col>}
            {!props.disabled && <Col span={3}>操作</Col>}
          </Row>
          {rules.map((item, index) => {
            return (
              <RuleItem
                {...props}
                value={item}
                index={index + 1}
                key={item.id}
                variable={props.variable}
                using_variables={props.using_variables}
                disabled={props.disabled}
                onChange={handleChange.bind(this, item.id)}
                operatorOptions={props.operator}
                onDel={del.bind(this, index)}
                onMove={move.bind(this, item, index)}
                len={rules.length}
                form={props.form}
                codes={props.codes}
                isOld={props.isOld}
                compareData={props.compareData[index]}
                isCompare={props.isCompare}
                strategyId={props.id}
              />
            );
          })}
        </div>
      )}
    </>
  );
}
